﻿using System;
using System.Net;
using System.Windows.Forms;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Tools.Ribbon;

using AFS.VisitationRequestTool.Addin.Properties;
using AFS.VisitationRequestTool.Addin.XML;
//using AFS.VisitationRequestTool.Addin.SharePoint;
using AFS.VisitationRequestTool.Addin.Entities;
using AFS.VisitationRequestTool.Addin.Variables;
using AFS.VisitationRequestTool.Addin.Common;
using AFS.VisitationRequestTool.Addin.Components;
using AFS.VisitationRequestTool.Addin;

namespace AFS.VisitationRequestTool.Addin
{
    public partial class Ribbon
    {
        //WindowFormRegionCollection formRegions;

        AppointmentItem appointmentItem;
        VisitationRequest visitationRequest;
        ProgressForm currentProgressForm;

        Settings settings = new Settings();
        RequestDetailsFormRegion requestDetailsFormRegion;

        private void Ribbon_Load(object sender, RibbonUIEventArgs e)
        {
            Logger.Info(String.Format("Entered. e.RibbonUI-->{0}", e.RibbonUI.ToString()));
            InitializeRibbon();
        }

        private void InitializeRibbon()
        {
            Logger.Info("Entered");
            Inspector inspector = this.Context as Inspector;
            // requestDetailsRegion = Globals.FormRegions[inspector].AFSRequestDetailsForm;

            // Load handler hides Custom Ribbon if not meeting instance
            if (inspector.CurrentItem is AppointmentItem &&
                ((AppointmentItem)inspector.CurrentItem).MeetingStatus != OlMeetingStatus.olNonMeeting) //Check to make sure we're dealing with a meeting item
            {
                appointmentItem = (AppointmentItem)inspector.CurrentItem;

                if ((appointmentItem.ItemProperties[Property.RequestSubmitted] != null && (bool)appointmentItem.ItemProperties[Property.RequestSubmitted].Value) ||
                    (appointmentItem.ItemProperties[Property.Filename] != null && appointmentItem.ItemProperties[Property.Filename].Value.ToString().Length > 0))
                {
                    Logger.Info(String.Format("Request already submitted."));

                    btnUploadToSharepoint.Enabled = false;
                }
                else
                {
                    btnUploadToSharepoint.Enabled = true;
                    //Globals.ThisAddIn.Application.ActiveInspector()
                    requestDetailsFormRegion = Globals.FormRegions[inspector].AFSRequestDetailsForm;
                }
                //Globals.RibbonLoaded = true;
            }
            else // If some kind of item other than appointment type, hide add-in elements as well
            {
                this.tab1.Visible = false;
                this.group1.Visible = false;
                this.btnUploadToSharepoint.Visible = false;
            }
        }

        private void btnUploadToSharepoint_Click(object sender, RibbonControlEventArgs e)
        {
            Logger.Info(String.Format("Entered. e.Control.Id-->{0}", e.Control.Id));

            try
            {
                CreateVisitationRequest();
            }
            catch (System.Exception ex)
            {
                if (currentProgressForm != null)
                    currentProgressForm.Close();

                Logger.Error(ex.ToString());
                MessageBox.Show(ErrorMessages.ProgramException);
            }
        }

        public void CreateVisitationRequest()
        {
            Logger.Info("Entered");

            try
            {
                StringBuilder errorMessages = requestDetailsFormRegion.HaveAllRequiredFieldsEnteredInRequestForm();
                visitationRequest = new VisitationRequest(appointmentItem);
                errorMessages.Append(visitationRequest.ValidateAppointment());

                if (errorMessages.Length > 0)
                {
                    MessageBox.Show(errorMessages.ToString());
                }
                else
                {
                    currentProgressForm = new ProgressForm();
                    currentProgressForm.Show();
                    //infoPathFormData = InfoPathFormWriter.CreateForm(requestDetailsFormRegion, appointmentItem); // Build our InfoPath form on current thread
                    visitationRequest.FormData = InfoPathFormWriter.CreateForm(requestDetailsFormRegion, appointmentItem); // Build our InfoPath form on current thread
                    this.backgroundWorker.RunWorkerAsync();
                }
            }
            catch (System.Exception ex)
            {
                if (currentProgressForm != null)
                    currentProgressForm.Close();

                Logger.Error(ex.ToString());
                MessageBox.Show(ErrorMessages.ProgramException);
            }
        }

        /// <summary>
        /// Background Worker Process: Required for progress form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {

            //string cancel = e.Result == null ? "e.Result is null" : e.Result.ToString();
            //Logger.Info(String.Format("Entered. e.Control.Id-->{0}", e.Argument));
            Logger.Info("Entered");

            try
            {
                //string documentID = String.Empty;
                //string submittedFormName = String.Empty;
                //string userName = String.Empty;               

                this.btnUploadToSharepoint.Enabled = false;

                // documentID = visitationRequest.GetDocumentItemID(); // SharePointUtility.GetDocumentItemID();
                // userName = appointmentItem.Session.CurrentUser.Name;
                // submittedFormName = String.Concat(userName, " - ", documentID);
                // visitationRequest.FormName = String.Concat(userName, " - ", documentID);
                // visitationRequest.UploadToVisitationRequestLibrary(infoPathFormData, submittedFormName);
                // UploadToVisitationRequestLibraryNew(infoPathFormData, submittedFormName);

                visitationRequest.UploadToVisitationRequestLibrary();
                this.requestDetailsFormRegion.txtFileName_Hidden.Text = visitationRequest.FormName;
                //this.requestDetailsFormRegion.txtFileName_Hidden.Text = submittedFormName;
                SetRequestSubmittedHiddenCheckBox(true);
                MessageBox.Show(PopUpText.MessageBoxSubmitSuccess);
                backgroundWorker.ReportProgress(100);
            }

            catch (System.Exception ex)
            {
                Logger.Error(ex.ToString());
                MessageBox.Show(ErrorMessages.ProgramException);
                this.btnUploadToSharepoint.Enabled = true;
            }
            finally
            {
                GC.Collect();
            }
        }

        /// <summary>
        /// Background Worker Process: Reenables ribbon button & closes form 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            // Commented out per suggested work-around in requirement 3.04.1 notes
            //this.btnUploadToSharepoint.Enabled = true;
            Logger.Info("Entered");
            this.currentProgressForm.Close();
        }

        private void SetRequestSubmittedHiddenCheckBox(bool isSubmitted)
        {
            this.requestDetailsFormRegion.chkSubmitted.Checked = isSubmitted;
        }       
    }

}
